<template>
    <div class="login_container">
        <el-row>
            <el-col :span="12" :xs="0"></el-col>
            <el-col :span="12" :xs="24">
                <el-form class="login_form" :model="loginForm" :rules="rules" ref="loginForms">
                    <h1>Hello</h1>
                    <h2>欢迎登录牛场智慧交互管理平台</h2>
                    <el-form-item prop="phone">
                        <el-input v-model="loginForm.phone" :prefix-icon="Iphone" placeholder="请输入手机号" size="large"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="loginForm.password" :prefix-icon="Lock" show-password type="password" placeholder="请输入密码" size="large"></el-input>
                    </el-form-item>
                    <el-form-item prop="code" class="verifyCodeBox">
                        <el-input v-model="loginForm.code" :prefix-icon="Tickets" placeholder="请输入验证码" size="large"></el-input>
                        <img class="verifyCodeImg" @click="updateVerifyCodeImg" :src="verifyCodeImg"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button :loading="loading" class="login_btn" type="primary" size="large" @click="login">登录</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { User, Lock, SetUp, Iphone, Tickets } from '@element-plus/icons-vue' // 引入 element-plus 图标
import { reactive, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time' // 获取当前时间
import { reqGetVerifyCode } from '@/api/user'
import { nanoid } from 'nanoid'

// 生成一个uuid
const uuid = ref(null)
uuid.value = nanoid()

// 引入用户相关小仓库
import useUserStore from '@/store/modules/user'
let userStore = useUserStore()

// 获取路由器
let $router = useRouter()
// 获取路由对象
let $route = useRoute()

// 收集账号与密码的数据
let loginForm = reactive({ phone: '19988886666', password: '123456', code: '', uuid: uuid.value })
// 登录按钮加载状态
let loading = ref(false)
// 获取表单实例
let loginForms = ref()
// 自定义校验规则函数
const validatorUserName = (rule, value, callback) => {
    // rule 即为校验规则对象
    // value 即为表单元素文本内容
    // callback函数 符合条件放行，不符合条件，注入错误信息
    if(value.length >= 1){
        callback()
    }else{
        callback(new Error('请输入账号'))
    }
}
const validatorPassword = (rule, value, callback) => {
    if(value.length >= 1){
        callback()
    }else{
        callback(new Error('请输入密码'))
    }
}
const validatorCode = (rule, value, callback) => {
    if(value.length != ''){
        callback()
    }else{
        callback(new Error('请输入验证码'))
    }
}

// 表单验证规则
const rules = {
    // 规则对象属性
    /**
     * required: 必填项
     * min: 文本最小长度
     * max: 文本最大长度
     * message: 错误提示信息
     * trigger: 触发表单校验的时机 change > 文本发送变化时触发，blur > 失去焦点时触发
     */
     phone:[
        // 使用自定义校验规则
        { trigger: 'blur', validator: validatorUserName }
    ],
    password: [
        // 使用自定义校验规则
        { trigger: 'blur', validator: validatorPassword }
    ],
    code: [
        // 使用自定义校验规则
        { trigger: 'blur', validator: validatorCode }
    ]
}

// 登录按钮回调
const login = async () => {
    // 保证全部表单校验通过再发请求，接收一个回调函数，或返回一个 Promise 对象
    await loginForms.value.validate()
    // 按钮loading状态
    loading.value = true
    // 在组件中，并不知道登录成功还是失败
    // 调用这个登录方法（加了 await/async），会返回一个 Promise 对象
    try{
        // 登录成功
        await userStore.userLogin(loginForm) // 调用仓库中的登录方法，携带收集的数据
        // 编程式导航跳转首页
        // 跳转判断，判断路由中是否有query参数，没有才跳转首页
        // if($route.query.redirect){
        //     $router.push(`${$route.query.redirect}`)
        //     console.log('退出登录带参数', `${$route.query.redirect}`)
        // }else{
        //     $router.push('/')
        // }
        await userStore.userMenu() // 获取动态菜单
        const goPath = userStore.roleMenu[0].children[0].path
        $router.push(`${goPath}`)
        // $router.push('/')
        // 登录成功提示信息
        ElNotification({
            type: 'success',
            message: '欢迎回来',
            title: `HI, ${userStore.username}, ${getTime()}好` // 模板字符串拼接
        })
        loading.value = false
    }catch(error){
        loading.value = false
        // 登录失败提示信息
        // ElNotification({
        //     type: 'error',
        //     message: error.message
        // })
    }
}

// 获取验证码
let verifyCodeImg = ref('')
const getVerifyCode = async () => {
    let res = await reqGetVerifyCode({
        uuid: uuid.value
    })
    verifyCodeImg.value = res.data
}

// 更新验证码图片
const updateVerifyCodeImg = () => {
    let new_uuid = nanoid()
    uuid.value = new_uuid
    loginForm.uuid = new_uuid
    getVerifyCode()
}

// 组件挂载完毕
onMounted(() => {
    getVerifyCode()
})

// 监听回车键，登录
window.document.onkeyup = (event) => {
    if (event.keyCode === 13) {
        console.log('按了回车键')
        login()
    }
}
</script>

<style scoped lang="scss">
    .login_container{
        width: 100%;
        height: 100vh;
        background-image: url('@/assets/images/background.jpg');
        background-size: cover;
        background-repeat: no-repeat;
        .login_form{
            width: 75%;
            top: 30vh;
            position: relative;
            background-image: url('@/assets/images/login_form.png');
            background-size: cover;
            background-repeat: no-repeat;
            padding: 40px;
            :deep(.verifyCodeBox){
                .verifyCodeImg{
                    height: 40px; 
                    border-radius: 3px;
                    margin-left: 10px;
                    cursor: pointer;
                    width: 200px;
                }
                .el-form-item__content{
                    display: flex;
                    flex-wrap: nowrap;
                }
            }
            h1{
                color: #ffffff;
                font-size: 40px;
            }
            h2{
                font-size: 18px;
                color: #ffffff;
                margin: 20px 0;
            }
            .login_btn{
                width: 100%;
            }
        }
    }
</style>